<template>
  <div class="bindPhone">
    <FormPanel ref="FormPanel" :cols="1" :list="formList" formType="edit" :isSubmitBtn="false" />
    <div class="bindPhoneBtn">
      <el-button type="primary" @click="changeHandle">保存</el-button>
      <!-- <el-button type="" class="getCode" @click="getCode">获取验证码</el-button> -->
    </div>
  </div>
</template>

<script>
import {getUserInfoList,supereditpassword,sendSms,updatePhone} from '@/api/common/auth/userInfo/index.js'
import { logoutJwt} from '@/api/login/index';
import store from '@/store';
import { authority } from '@/utils/authMixin';
import { mapActions, mapState } from 'vuex';
import * as types from '@/api/login/types';
import { sleep } from '@/utils';
import { getUser, getToken, removeToken, removeUser, removeDataType, removeAppId ,setToken, setDataType, setAppId, jsEncrypt } from '@/assets/js/auth';
export default {
  name: 'bindPhone',
  data() {
    return {
      userCode:"",
      employeeName:"",
      formList: this.createFormList(),
      codeMsg:'获取验证码',
      timer:null,
      count:"",
      isDisabled:false,
    };
  },
  created () {
    this.getUserInfo()
    this.getCookie()
  },
  computed: {
    ...mapState('app', ['btnLoading']),
  },
  methods:{
    ...mapActions('app', ['createLoginInfo']),
        getCookie(){
          let allCookie=document.cookie.split(';')
          allCookie.forEach(x=>{
            if(x.indexOf('dataType') > -1 ){
              this.dataType=x.split('=')[1]
              }
          })
          //判断是否为车厂10461003
          console.log(this.dataType,"dataType")
          if(this.dataType == 10461003){
            console.log(this.dataType,"车厂")
          }
        },
         //请求数据
        async getUserInfo(){
            await getUserInfoList().then(res=>{
              console.log(res.data,"data")
                this.formList[0].initialValue = res.data.employeeNo
                this.formList[1].initialValue = res.data.employeeName
                this.formList[2].initialValue = res.data.userCode
                this.formList[3].initialValue = res.data.mobilePhone
            }).catch()
        },
        createFormList() {
          const validatePhone = (rule, value, callback) => {
            if (_.isEmpty(value)) {
              callback(new Error('请输入正确的手机号'));
            } else {
              callback();
            }
          };
          const validateVerifyCode = (rule, value, callback) => {
            if (_.isEmpty(value)) {
              callback(new Error('请输入验证码'));
            } else {
              callback();
            }
          };
          return [
            {
              type: 'INPUT',
              label: '员工编号',
              fieldName: 'userCode1',
              disabled:true,
              initialValue: "2",
              style: { width: '200px' },
            }
            ,{
              type: 'INPUT',
              label: '员工姓名',
              fieldName: 'employeeName',
              disabled:true,
              initialValue: '1',
              style: { width: '200px' },
            },{
              type: 'INPUT',
              label: '登陆账号',
              fieldName: 'userCode',
              disabled:true,
              initialValue: '',
              style: { width: '200px' },
            },{
              type: 'INPUT',
              label: '原手机号',
              fieldName: 'mobilePhone',
              placeholder: '请输入',
              initialValue: '',
              disabled:true,
              style: { width: '200px' },
            },{
              type: 'INPUT',
              label: '绑定手机号',
              fieldName: 'bindPhone',
              placeholder: '请输入',
              initialValue: '',
              style: { width: '300px' },
              maxlength:11,
              unitRender: () => {
                return <el-button slot="append" disabled={this.isDisabled} onClick={this.getCode}>{this.codeMsg}</el-button>;
              },

              rules: [{ required: true, trigger: 'blur', validator: validatePhone },
            { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
            { pattern: /^1[3456789]\d{9}$/, message: '手机号码有误', trigger: 'blur' }]
            },{
              type: 'INPUT',
              label: '验证码',
              fieldName: 'bindCheckCode',
              placeholder: '请输入',
              initialValue: '',
              style: { width: '200px' },
              rules: [{ required: true, trigger: 'blur', validator: validateVerifyCode }]
            },]
          },

      //获取验证码
      getCode(){
        console.log("获取验证码",this.formList[4].initialValue)
        let g = /^1[3456789]\d{9}$/
        if(g.test(this.formList[4].initialValue)){
          this.isDisabled=true
          sendSms(this.formList[4].initialValue).then(res=>{
            if(res.resultCode == 200){
                this.$message({
                    type: 'success',
                    message: '验证码发送成功'
                })
                const TIME_COUNT = 60;
                if (!this.timer) {
                  this.count = TIME_COUNT;
                  this.timer = setInterval(() => {
                    if (this.count > 0 && this.count <= TIME_COUNT) {
                      this.count--;
                      this.codeMsg=`${this.count}s`
                    } else {
                      clearInterval(this.timer);
                      this.codeMsg=`获取验证码`
                      this.timer = null;
                    }
                  }, 1000);
                }
                this.isDisabled=false
              }else{
                this.$message({
                    type: 'warning',
                    message: `${res.errMsg}`
                })
                this.isDisabled=false
              }
          })
        }/* else{
          this.$message({
              type: 'info',
              message: '请输入正确得手机号'
          })
        } */
      },
      // 修改
      async changeHandle(val){
        console.log(this.formList,"this.formList")
        if(this.formList[5].initialValue && this.formList[4].initialValue){
            const param = {
                phone: this.formList[4].initialValue,
                checkCode: this.formList[5].initialValue,
                type:1,
                // userCode: val.userCode,
            };
            updatePhone(param)
            .then(res => {
                if(res.resultCode == 200){
                    this.$message({
                        type: 'success',
                        message: '保存成功'
                    })
                    this.$router.push("/admin/auth/userInfo")
                    clearInterval(this.timer);
                    this.codeMsg=`获取验证码`
                    this.isDisabled=false

                    this.formList[4].initialValue = ''
                    this.formList[5].initialValue = ''

                    this.formList[4].rules = []
                    this.formList[5].rules = []
                }else if(res.resultCode == 996){
                  this.open2()
                }
            }).catch(err => {})
        }else{
          //this.$message.error('新旧密码不能一样');
        }
      },

      //手机号已绑定是否继续绑定
    open2() {
        this.$confirm('手机号已绑定其他账号，如继续绑定，则将于原账号进行解绑', '提示', {
          confirmButtonText: '继续绑定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            let  param = {
                phone: this.formList[4].initialValue,
                type:2,
            };
            updatePhone(param).then(res=>{
              console.log(res,"是否继续绑定")
                this.$message({
                  type: 'success',
                  message: '绑定成功!'
                });
                this.$router.push("/admin/auth/userInfo")
                clearInterval(this.timer);
                this.codeMsg=`获取验证码`
                this.isDisabled=false
                this.formList[4].initialValue = ''
                this.formList[5].initialValue = ''

                this.formList[4].rules = []
                this.formList[5].rules = []
            })
          /* this.$message({
            type: 'success',
            message: '删除成功!'
          }); */
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      },
      // 重置
      // RestHandle(){
      //   this.$refs.FormPanel.RESET_FORM()
      //   this.getUserInfo()
      // },

  }
};
</script>

<style lang="less" scoped>
.bindPhone{
  .bindPhoneBtn{
    width: 100%;
    text-align: center;
    /* position: relative;
    .getCode{
        position: absolute;
        left: 18vw;
        top: -5.7vw;
    } */
  }
}
</style>
